package com.wmada.toolkit.common;

import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * The Thread Safe date format.
 *
 * @author will.ma
 */
public class DateFormat extends ThreadLocal<SimpleDateFormat> {

    public static final DateFormat DATE_FORMAT               = new DateFormat("yyyy-MM-dd");
    public static final DateFormat TIME_FORMAT               = new DateFormat("HH:mm:ss");
    public static final DateFormat DATETIME_FORMAT           = new DateFormat("yyyy-MM-dd HH:mm:ss");
    public static final DateFormat DATETIME_FORMAT_UNDERLINE = new DateFormat("yyyyMMdd_HHmmss");
    public static final DateFormat DATETIME_FORMAT_US        = new DateFormat("EEE MMM dd hh:mm:ss Z yyyy", Locale.US);

    private String            pattern;
    private Locale            locale;
    private DateFormatSymbols formatSymbols;

    @Override
    public SimpleDateFormat initialValue() {
        if (pattern != null) {
            if (locale == null && formatSymbols == null) {
                return new SimpleDateFormat(pattern);
            } else if (locale != null) {
                return new SimpleDateFormat(pattern, locale);
            } else {
                return new SimpleDateFormat(pattern, formatSymbols);
            }
        }
        return new SimpleDateFormat();
    }

    /**
     * Instantiates a new Ts date format.
     */
    public DateFormat() {

    }

    /**
     * Instantiates a new Ts date format.
     *
     * @param pattern the pattern
     */
    public DateFormat(String pattern) {
        this.pattern = pattern;
    }

    /**
     * Instantiates a new Ts date format.
     *
     * @param pattern the pattern
     * @param locale  the locale
     */
    public DateFormat(String pattern, Locale locale) {
        this.pattern = pattern;
        this.locale = locale;
    }

    /**
     * Instantiates a new Ts date format.
     *
     * @param pattern       the pattern
     * @param formatSymbols the format symbols
     */
    public DateFormat(String pattern, DateFormatSymbols formatSymbols) {
        this.pattern = pattern;
        this.formatSymbols = formatSymbols;
    }

    /**
     * Format string.
     *
     * @param date the date
     * @return the string
     */
    public String format(Date date) {
        return get().format(date);
    }

    /**
     * Parse date.
     *
     * @param source the source
     * @return the date
     */
    public Date parse(String source) {
        return parse(source, TimeUtils.now());
    }

    /**
     * Parse date.
     *
     * @param source       the source
     * @param defaultValue the default value
     * @return the date
     */
    public Date parse(String source, Date defaultValue) {
        try {
            return get().parse(source);
        } catch (ParseException e) {
            return defaultValue;
        }
    }

}
